/*
 * Copyright (c) 2024 endless-sky
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

#include <atomic>
#include <memory>
#include <thread>
#include <mutex>
#include <map>
#include <functional>
#include <nlohmann/json.hpp>
#include "utils_noncopyable.h"
#include "common_media_define.h"
#include "media_frame.h"
#include "utils_callback_list.h"
#include "hal_audio.h"


namespace El {
namespace Media {

/**
 * @brief 音频输入源类型
 */
enum class AudioInputSource {
    BUILTIN = 0,  // 内置麦克风
    USB           // USB音频设备
};

class MediaAudioManager {
    DISALLOW_COPY_AND_MOVE(MediaAudioManager);
    MediaAudioManager(int32_t ch);
    ~MediaAudioManager();

public:
    using Proc = std::function<void(const MediaFramePtr &)>;

    static MediaAudioManager &GetInstance(int32_t ch);

    int32_t Start(const Proc &proc);

    void Stop(int32_t handle);

    /**
     * @brief 获取当前音频输入源
     * @return 当前音频源类型
     */
    AudioInputSource GetCurrentAudioSource() const;

private:
    void AudioThread();
    bool StartAudio();
    void StopAudio();
    bool StartUsbAudio(const std::string& cardId);
    void StopUsbAudio();

private:
    int32_t ch_{0};
    std::atomic<bool> start_{false};
    std::mutex mutex_;

    Utils::CallbackList<void, const MediaFramePtr &> callbackManager_;

    std::unique_ptr<std::thread> audioThread_;

    // USB音频相关
    AudioInputSource currentSource_{AudioInputSource::BUILTIN};
    std::string usbCardId_;
};

} // namespace Media
} // namespace El